package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;

    private String method;
    private String uri;
    private String protocol;
    private Map<String,String> headers=new HashMap<>();

    public HttpServletRequest(Socket socket) throws IOException, EmptyRequestException {
        this.socket=socket;
        parseRequestLine();
        parseHeaders();
        parseContent();
    }

    private void parseRequestLine() throws IOException, EmptyRequestException {
        String line=readLine();
        if (line.isEmpty()){
            throw new EmptyRequestException();
        }
        String[] array=line.split("\\s");
        method=array[0];
        uri=array[1];
        protocol=array[2];
    }
    private void parseHeaders() throws IOException {
        String line;
        while (!(line=readLine()).isEmpty()){//当读取的消息头不为空时继续循环
            String[] strings=line.split(":\\s");
            headers.put(strings[0],strings[1]);
        }
    }
    private void parseContent(){}

    private String readLine() throws IOException {
        InputStream in=socket.getInputStream();
        char pre='e',cur='f';
        StringBuilder builder=new StringBuilder();
        int d;
        while ((d=in.read())!=-1){
            cur=(char)d;
            if (pre==13&&cur==10){
                break;
            }
            builder.append(cur);
            pre=cur;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }
    public String getHeader(String name){
        return headers.get(name);
    }

}
